package com.redis.demo.rabbitmq.Work;

import com.rabbitmq.client.*;
import com.redis.demo.rabbitmq.Constants.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer2 {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUALHOST);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(Constants.WORK_QUEUE,true,false,false,null);
        //自动确认
        /*consumerTag:消费者标签
         *envelope;交换机信息
         *properties配置信息
         *从队列中接收消息后收到的逻辑
         *
         * */
        DefaultConsumer consume=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //空
                System.out.println("接收到消息"+new String(body));
            }
        };
        channel.basicConsume(Constants.WORK_QUEUE,true,consume);
        System.out.println("接收到消息");
        Thread.sleep(2000);
        //启动的时候要先启动消费者，如果先启动生产者的话，就会在启动其中一个消费者的时候瞬间吃掉所有的消息，另一个消费者就一个消息都吃不到了。
        /*channel.close();
        connection.close();*/


    }
}
